//连接的集合
var connection_cache = {};
var sockjs = require('sockjs');
var notify = {
	conns: connection_cache,
	init: function(app, prefix) {
		var sockjs_instance = sockjs.createServer();
		setTimeout(function() {
			sockjs_instance.installHandlers(app._server, {
				prefix: prefix || '/sock_notify'
			});
			sockjs_instance.on("open", function(conn) {
				console.log("open:", conn);
			});
			sockjs_instance.on('connection', function(conn) {
				if (!conn) {
					return;
				}
				conn.on('data', function(message) {
					// var d = domain.create();
					// d.on('error', function(e) {
					// 	console.log("--------------------\nSock Error:", String(e), "\n", e.stack, "\n--------------------");
					// 	notify.send(conn, "error", e.message || e);
					// });
					// d.run(function() {
					// 	// console.log(conn,sockjs_instance);
					try {
						var json_data = JSON.parse(message);
					} catch (e) {
						e.message += "(SOCK JSON 解析出错)"
						Throw(e);
					}
					notify.emit(json_data.type, conn, json_data.value);
					// });
				});
				conn.on('close', function() {
					console.log("close", conn && conn.id);
					notify.emit("close", conn);
				});
			});
		});
	},
	send: function(conn, type, value) {
		if (conn instanceof Array) {
			conn.forEach(function(conn_single) {
				notify.send(conn_single, type, value)
			});
			return;
		}
		console.log("SOCK SEND:", {
			s_key: conn.s_key,
			s_info: conn.s_info
		});
		conn.write(JSON._stringify({
			type: type,
			toString: JSON.stringify(value)
		}));
	},
};

events.objToEventEmitter(notify);
module.exports = notify;

var domain = require("domain");